package com.example.ssm.aspect;

import com.example.ssm.annotation.UserCodeToUsername;
import com.example.ssm.entity.UserInfo;
import com.example.ssm.service.UserInfoService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;

@Aspect
@Component
public class UserCodeToUsernameAspect {

    @Autowired
    private UserInfoService userInfoService;

    @Around("execution(* com.example.ssm.controller.*.*(..))")
    public Object convertUserCodeToUsername(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("AOP开始执行...");
        Object result = joinPoint.proceed();
        
        if (result == null) {
            return result;
        }

        if (result instanceof List) {
            List<?> list = (List<?>) result;
            for (Object obj : list) {
                processObject(obj);
            }
        } else {
            processObject(result);
        }

        return result;
    }

    private void processObject(Object obj) throws IllegalAccessException {
        if (obj == null) {
            return;
        }

        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            if (field.isAnnotationPresent(UserCodeToUsername.class)) {
                field.setAccessible(true);
                String usercode = (String) field.get(obj);
                if (usercode != null) {
                    UserInfo userInfo = userInfoService.getByUsername(usercode);
                    if (userInfo != null) {
                        field.set(obj, userInfo.getUsername());
                    }
                }
            }
        }
    }
} 